﻿' ----------------------------------------------------------------------------------
' Microsoft Developer & Platform Evangelism
' 
' Copyright (c) Microsoft Corporation. All rights reserved.
' 
' THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
' EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
' OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
' ----------------------------------------------------------------------------------
' The example companies, organizations, products, domain names,
' e-mail addresses, logos, people, places, and events depicted
' herein are fictitious.  No association with any real company,
' organization, product, domain name, email address, logo, person,
' places, or events is intended or should be inferred.
' ----------------------------------------------------------------------------------

Imports Microsoft.Samples.WindowsPhoneCloud.Web.UserAccountWrappers
Imports System.Globalization

Namespace Infrastructure

    Public Class TableRequestValidator
        Inherits StorageRequestValidator
        Private ReadOnly userPrivilegesRepository As IUserPrivilegesRepository

        Public Sub New()
            Me.New(New FormsAuthenticationService(), New AccountMembershipService(), New UserTablesServiceContext())
        End Sub

        <CLSCompliant(False)>
        Public Sub New(ByVal formsAuth As IFormsAuthentication, ByVal membershipService As IMembershipService, ByVal userPrivilegesRepository As IUserPrivilegesRepository)
            MyBase.New(formsAuth, membershipService)
            Me.userPrivilegesRepository = userPrivilegesRepository
        End Sub

        Protected Overrides Function OnValidateRequest(ByVal userId As String, ByVal context As HttpContext) As Boolean
            If Not Me.CanUseTables(userId) Then
                context.Response.EndWithDataServiceError(401, "Unauthorized", "You have no permission to use tables.")
            End If

            Dim tableName = StorageRequestAnalyzer.GetRequestedTable(context.Request)
            If Not Me.CanUseTable(userId, tableName, context.Request) Then
                context.Response.EndWithDataServiceError(401, "Unauthorized", "You have no permission to use this table.")
            End If

            Return True
        End Function

        Private Function CanUseTable(ByVal userId As String, ByVal tableName As String, ByVal request As HttpRequest) As Boolean
            Dim publicTablePrivilege = String.Format(CultureInfo.InvariantCulture, "{0}{1}", tableName, PrivilegeConstants.PublicTablePrivilegeSuffix)
            If Not Me.userPrivilegesRepository.PublicPrivilegeExists(publicTablePrivilege) Then
                Dim accessTablePrivilege = String.Format(CultureInfo.InvariantCulture, "{0}{1}", tableName, PrivilegeConstants.TablePrivilegeSuffix)
                If Not Me.userPrivilegesRepository.HasUserPrivilege(userId, accessTablePrivilege) Then
                    ' Check if the user is listing the available tables or creating a new table.
                    Return StorageRequestAnalyzer.IsListingTables(request) OrElse StorageRequestAnalyzer.IsCreatingTable(request, tableName)
                End If
            End If

            Return True
        End Function

        Private Function CanUseTables(ByVal userId As String) As Boolean
            Return Me.userPrivilegesRepository.HasUserPrivilege(userId, PrivilegeConstants.TablesUsagePrivilege)
        End Function
    End Class
End Namespace